const sqlGeneratorModel = require('../models/sqlGeneratorModel');
const db = require('../config/database');

class SQLGeneratorController {
  // TODO: 实现generateSQL方法
  async generateSQL(req, res) {
    // 处理自然语言转SQL请求
    try {
        const { description, dbTable = 'restaurant_reviews', promptType = 'advanced' } = req.body;
        
        if (!description) {
          return res.status(400).json({ 
            error: '缺少查询描述', 
            code: 'MISSING_DESCRIPTION' 
          });
        }
        
        // 验证提示词类型
        const validPromptTypes = ['basic', 'improved', 'advanced'];
        if (promptType && !validPromptTypes.includes(promptType)) {
          return res.status(400).json({ 
            error: '不支持的提示词类型', 
            code: 'INVALID_PROMPT_TYPE',
            valid_types: validPromptTypes
          });
        }
        
        const result = await sqlGeneratorModel.generateSQL(description, dbTable, promptType);    
    
        res.json({
          sql: result.sql,
          metadata: result.metadata,
        });
      } catch (error) {
        res.status(500).json({ 
          error: error.message, 
          code: 'GENERATION_FAILED' 
        });
      }
  }

  // TODO: 实现executeNLQuery方法
  async executeNLQuery(req, res) {
    // 处理自然语言转SQL并执行查询请求
    try {
      const { description, dbTable = 'restaurant_reviews', promptType = 'advanced' } = req.body;
      
      if (!description) {
        return res.status(400).json({ 
          error: '缺少查询描述', 
          code: 'MISSING_DESCRIPTION' 
        });
      }
      
      // 验证提示词类型
      const validPromptTypes = ['basic', 'improved', 'advanced'];
      if (promptType && !validPromptTypes.includes(promptType)) {
        return res.status(400).json({ 
          error: '不支持的提示词类型', 
          code: 'INVALID_PROMPT_TYPE',
          valid_types: validPromptTypes
        });
      }
      
      const result = await sqlGeneratorModel.executeSQL(description, dbTable, promptType);    
      
      res.json({
        sql: result.sql,
        metadata: result.metadata,
        queryResults: result.queryResults,
      });
    } catch (error) {
      res.status(500).json({ 
        error: error.message, 
        code: 'EXECUTION_FAILED' 
      });
    }
  }
  
  // TODO: 实现testSQLGeneration方法
  async testSQLGeneration(req, res) {
    // 处理批量测试SQL生成
  }
}

module.exports = new SQLGeneratorController();